import re

from django.contrib.auth import get_user_model
from django.conf import settings
import redis
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

User = get_user_model()


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        """
        验证手机号码
        :param mobile:
        :return:
        """
        # 验证手机号是否注册
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError('用户已存在')

        # 验证手机号是合法
        if not re.match(settings.REGEX_MOBILE, mobile):
            raise serializers.ValidationError('手机号码非法')

        # 验证发送频率
        r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD, db=0,
                        charset="utf8", decode_responses=True)
        redis_code = r.get(str(mobile))
        if redis_code:
            raise serializers.ValidationError('距离上一次发送未超过60s')

        return mobile


class RegisterSerializer(serializers.ModelSerializer):
    """
    注册序列化类
    """
    code = serializers.CharField(required=True, max_length=4, min_length=4, label="验证码", write_only=True,
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误",
                                 }, help_text="验证码")
    username = serializers.CharField(label="用户名", required=True, allow_blank=True, help_text="用户名", validators=[
        UniqueValidator(queryset=User.objects.all(), message="用户已存在")])
    password = serializers.CharField(style={'input_type': 'password'}, label="密码", help_text="密码", write_only=True)

    # def create(self, validated_data):
    #     """
    #     保存密文密码，也可以使用信号量的方式
    #     :param validated_data:
    #     :return:
    #     """
    #     user = super(RegisterSerializer, self).create(validated_data=validated_data)
    #     user.set_password(validated_data["password"])
    #     user.save()
    #     return user

    def validate_code(self, code):
        """
        验证验证码
        :param code:
        :return:
        """
        mobile = self.initial_data['username']
        # 验证验证码
        r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD, db=0,
                        charset="utf8",
                        decode_responses=True)
        redis_code = r.get(str(mobile))
        if not redis_code:
            raise serializers.ValidationError('验证码过期')
        if redis_code != code:
            raise serializers.ValidationError('验证码错误')

    def validate(self, attrs):
        """
        统一处理
        :param attrs:
        :return:
        """
        print(attrs)
        attrs["mobile"] = attrs["username"]
        del attrs["code"]
        return attrs

    class Meta:
        model = User
        fields = ("username", "code", "mobile", "password")


class DetailSerializer(serializers.ModelSerializer):
    """
    用户详情序列化类
    """
    class Meta:
        model = User
        fields = ("name", "gender", "birthday", "email", "mobile")
